package at.fhj.itm11.forum.beans;

import java.io.Serializable;

import javax.annotation.PostConstruct;
import javax.enterprise.context.RequestScoped;
import javax.enterprise.inject.Produces;
import javax.faces.bean.ManagedBean;
import javax.inject.Inject;
import javax.inject.Named;

import at.fhj.itm11.forum.service.RatingService;
import at.fhj.itm11.forum.service.dtos.PostDTO;
import at.fhj.itm11.forum.service.dtos.RatingDTO;
import at.fhj.itm11.forum.service.dtos.UserDTO;
import at.fhj.itm11.forum.util.ForumConstants;

@ManagedBean
@RequestScoped
public class RatingBean implements Serializable{

	/**
	 * 
	 */
	private static final long serialVersionUID = -8808311719494761873L;

	@Inject
	private AuthenticationBean authBean;
	
	@Inject
	@Named("ratingServiceImpl")
	private RatingService ratingService;
	
	@Produces
	private RatingDTO rating;
	
	@PostConstruct
	private void init() {
		rating = new RatingDTO();
		UserDTO user = (UserDTO) authBean.getSession().getAttribute(
				ForumConstants.SESSION_CURRENT_USER);
		rating.setUser(user);
	}
	
	public void ratePositively(PostDTO post) {
		rating.setPost(post);
		rating.setPositiveRating(true);
		ratingService.rate(rating);
		refreshStatistics(post);
	}
	
	public void rateNegatively(PostDTO post) {
		rating.setPost(post);
		rating.setPositiveRating(false);
		ratingService.rate(rating);
		refreshStatistics(post);
	}
	
	public void refreshStatistics(PostDTO post) {
		int[] statistics = ratingService.getRatingStatistics(post.getId());
		post.setPercentageOfPositiveRatings(statistics[0]);
		post.setPercentageOfNegativeRatings(statistics[1]);
		
		
	}
}
